package com.example.om_export.app.upload.controller;


import com.example.om_export.app.upload.service.UploadService;
import com.example.om_export.common.entity.Params;
import com.example.om_export.common.entity.Result;
import com.example.om_export.common.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传相关接口
 * @author wb-ycl473317
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    /**
     * 上传文件，支持批量
     * @param files 文件数据
     * @param docunid 所关联的文档id,如果为null则会随机生成一个uuid
     * @return 返回docunid值
     */
    @PostMapping({"save","save/guest"})
    public Result save(@RequestParam("file") MultipartFile[] files,
                       @RequestParam(value = "docunid",required = false) String docunid,
                       @RequestParam(value = "attType",required = false) String attType){
        return uploadService.save(files,docunid,attType);
    }

    /**
     * 根据 docunid 将对应附件改为可用 delState = 0
     * @param docunid
     * @return
     */
    @PutMapping("active")
    public Result active(@RequestBody String docunid){
        return uploadService.active(docunid);
    }

    /**
     * 根据 docunid 将对应附件改为可用 delState = 1
     * @param docunid
     * @return
     */
    @PutMapping("quiet")
    public Result quiet(@RequestBody String docunid){
        return uploadService.quiet(docunid);
    }

    @DeleteMapping("delete")
    public Result delete(String id){
        return uploadService.delete(id);
    }

    /**
     * 根据新增和删除的数组更新附件表
     * 附件都是选中后就上传的此时状态为 1（不可用），通过这个方法将附件变为有效或无效
     * @param params
     * addIds 新增的附件id数组
     * delIds 删除的附件id数组
     * @return
     */
    @PutMapping({"update","update/guest"})
    public Result update(@RequestBody Params params){
        return uploadService.update(params.getObj("addIds"),params.getObj("delIds"));
    }

    /**
     * 下载模板
     * @param name 模板名字
     */
    @GetMapping("down-template/{name}")
    public void downTemplate(HttpServletResponse response,@PathVariable String name){
        ClassPathResource classPathResource = new ClassPathResource("static/template_file/"+name);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        Map<String,String> map = new HashMap<>(16);
        map.put("user_info.xlsx","学员模板.xlsx");
        map.put("lesson.xlsx","课程模板.xlsx");
        map.put("org_dept.xlsx","学习成果认证单位模板.xlsx");
        map.put("user_info_admin.xlsx","终身学习成果认证制度管理员模板.xlsx");

        try {

            String fileName= URLEncoder.encode(map.get(name),"utf-8");
            ByteArrayOutputStream byteArrayOutputStream = FileUtil.InputStreamToByte(classPathResource.getInputStream());
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + byteArrayOutputStream.size());
            response.setContentType("application/octet-stream");

            ServletOutputStream outputStream = response.getOutputStream();
            byteArrayOutputStream.writeTo(outputStream);
            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
